<?php 
namespace Common\Service;
use Common\Util\HttpUtil;
use Common\Util\CacheUtils;
use Common\Util\ConfigUtils;

/**
 * 微信公众平台接口
 * @author liuyang 
 * V1.0
 */
class WeixinService {
	   
    const PREFIX = "CRM_";
	
	private static function _setCache($key,$val,$expire){
	    CacheUtils::set($key,$val,$expire);
	}
	
	private static function _getCache($key){
	    return CacheUtils::get($key); 
	}
	
	public static function getKey(){
		return ConfigUtils::getConfig("WEIXIN_MP_APPID");
	}
	public static function getSecret(){
	    return ConfigUtils::getConfig("WEIXIN_MP_SECRET");
	}
	/**
	 * 微信JS ticket
	 * @return Ambigous <mixed, unknown>
	 */
	/**
	 * 获取JStoken
	 * @return string 
	 */
	public static function getJsApiTicket(){
	    //缓存
		$jsapiTicket=self::_getCache("jsapi_ticket");
		//$jsapiTicket = null;
		if($jsapiTicket==null){
			$token=self::obtainAccessToken();
			$url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token."&type=jsapi";
		    $rst = array();
			$rstdata = json_decode(HttpUtil::curlGet($url),true);
			if($rstdata['ticket']){
				self::_setCache("jsapi_ticket",$rstdata['ticket'],3600);
				$jsapiTicket = $rstdata['ticket'];
			} 
		}
		return $jsapiTicket;
	
	}
	/**
	 * 授权接口URL
	 * @param  $param param list
	 * @return string
	 */
	public static function url($callback,$scope="snsapi_userinfo"){ 
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
		    .self::getKey()."&redirect_uri=".$callback
		."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect"; 
		return $url;
	}
	/**
	 * 上传多媒体文件
	 * @param  $type 微信API查看
	 * @param  $file 
	 * @return Ambigous <string, unknown>
	 */
	public static function uploadFile($type,$file){ 
		$data = array();
		$data['media']=$file;
		$token=self::obtainAccessToken(); 
		$url="http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=".$type; 
		$rststr = HttpUtil::curlPost($url,$data);  
		return $rststr; 
	}
	/**
	 * 下载文件
	 * @param unknown $mediaId
	 * @return filename
	 */
	public static function downloadFile($mediaId){
		$params = array(
				'access_token' => self::obtainAccessToken(),
				'media_id' => $mediaId,
		);
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?".http_build_query($params);
		 
		$file = HttpUtil::downloadRemoteFile("Uploads/votepic", $url);
		return $file;
	}
	  
	/**
	 * 拿到认证环
	 * @return Ambigous <mixed, unknown>
	 */
	public  static function obtainAccessToken(){ 
		$token= self::_getCache("access_token");
        if($token==null){
			$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::getKey()."&secret=".self::getSecret();
			$rstdata = json_decode(HttpUtil::curlGet($url),true);  
            self::_setCache("access_token",$rstdata['access_token'],3600);
            $token = $rstdata['access_token'];
        }
		return $token;
	}
	
	
	
	/**
	 * 网页授权登录环
	 * @param unknown $code
	 * @return mixed
	 */
	public static function obtainLoginAccessToken($code){
		$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".self::getKey()."&secret=".self::getSecret()."&code=".$code."&grant_type=authorization_code";
		$rstdata = json_decode(HttpUtil::curlGet($url),true);
		return $rstdata;
	}
	/**
	 * 网页授权后的获取的用户信息[昵称、OPENID]
	 * @param  $weixin_id toUserName
	 * @param  $access_token
	 * @return mixed
	 */
	public static function obtainLoginUserInfo($weixin_id,$access_token){
		$url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$weixin_id; 
		$rstdata = json_decode(HttpUtil::curlGet($url),true);
		return $rstdata;
	}
	/**
	 * 中文编码
	 * @param  $data
	 * @return mixed
	 */
	static function  _jsonEncodeWithCN($data) {
		return json_encode($data,JSON_UNESCAPED_UNICODE);
	}
	 /**
	  * 生成二维码
	  */
	public static function obtain2dcode(){
		$token=self::obtainAccessToken();  
		$url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token;
		$rst = array();
		$rst['expire_seconds']=1800;
		$rst['action_name']="QR_SCENE";//二维码类型，QR_SCENE为临时,QR_LIMIT_SCENE为永久
		$rst['action_info']['scene']['scene_id']=123;  
		$str='{"expire_seconds":1800,"action_name":"QR_SCENE","action_info":{"scene":{"scene_id":123}}}';
		$rstdata = json_decode(self::_send($url,self::_jsonEncodeWithCN($rst),"POST"),true); 
		//var_dump($rstdata);
		$url="http://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$rstdata['ticket'];  
		header ( "Content-type: image/jpg; charset=utf-8" );
		echo HttpUtil::curlGet($url);
	}
	
	/**
	 * 关注用户的个人信息
	 * @param unknown $weixin_id
	 * @return mixed
	 */
	public static function getuserinfo($weixin_id){
		$token=self::obtainAccessToken();
		$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$weixin_id;
		$rstdata = json_decode(HttpUtil::curlGet($url),true);
		return $rstdata;
	} 
	
	/**
	 * 图文回复
	 */
	public static function replyInfoToUserArray($touser,$token,$newstitle,$newspic,$newsurl){ 
		$rst = array();
		$rst['touser']=$touser;
		$rst['msgtype']="news";
		$news = array();
		$news['title']=$newstitle;
		$news['picurl']=$newspic;
		$news['url']=$newsurl;
		$news['description']="";
		$articles = array();
		$articles[] = $news;
		$rst['news']['articles']=$articles; 
		$url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$token; 
		$rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($rst)),true);;
		 //var_dump($rstdata);
		return $rstdata;
	}
	
	 /**
	  * 文本回复
	  * @param $touser toUserName
	  * @param  $txt
	  * @return mixed
	  */
	public static function replyInfoToUser($touser,$txt){
		$token=self::obtainAccessToken();
		$rst = array();
		$rst['touser']=$touser;
		$rst['msgtype']="text";
		$news = array();
		$rst['text']=array("content"=>$txt);
		$url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$token;
		 
		$rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($rst)),true);;
		return $rstdata;
	}
	
	/**
	 * 模板回复
	 */
	public static function replyTemplate($touser,$templateId,$data,$url){ 
	    $token = self::obtainAccessToken();
	    $rst = array();
	    $rst['touser']=$touser;
	    $rst['template_id']=$templateId;
	    $rst['url']=$url;
	    $rst['topcolor']='#FF0000';
	    foreach($data as $key=>$val){
	        $rst['data'][$key]= array("value"=>$val,'color'=>'#173177');
	    }
	    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
	    $rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($rst)),true);; 
	    //echo json_encode($rstdata);
	    return $rstdata;
	}
	/**
	 * 加载对应的标签
	 * @param unknown $tagname
	 */
	public static function getTagByName($tagname){
	    //$tagname = self::PREFIX.$tagname;
	    $list= self::_getCache("tag_list");
	    if($list == null){
    	    $token = self::obtainAccessToken();
    	    $url ="https://api.weixin.qq.com/cgi-bin/tags/get?access_token=".$token;
    	    $rstlist = HttpUtil::curlGetJson($url);
    	    $templist = $rstlist['tags'];
    	    $list = array();
    	    foreach($templist as $key=>$val){
    	        $list[$val['name']] = $val;
    	    } 
    	    CacheUtils::set("tag_list", $list, 24*3600);
	    }  
	    if(!isset($list[$tagname])){
	        CacheUtils::set("tag_list", null, 24*3600);
	        return null;
	    }else{
	        return $list[$tagname]['id']; 
	    } 
	}
	/**
	 * 为用户打标签
	 * @param  $openIds
	 * @param  $tagname
	 * @return mixed
	 */
	public static function addTag($openIds,$tagname){ 
	    $tagname = self::PREFIX.$tagname;
	    $tagid = self::getTagByName($tagname);
	    if(isset($tagid)){
    	    $token = self::obtainAccessToken();
    	    $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=".$token;
    	    $postData = array();
    	    if(is_array($openIds)){
    	       $postData['openid_list']=$openIds;
    	    }else{
    	       $postData['openid_list']=array($openIds);
    	    }
    	    $postData['tagid']=$tagid;
    	    $rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($postData)),true);
    	    //echo json_encode($rstdata);
    	    return $rstdata;
	    }else{
	        return false;
	    }
	}
	
	/**
	 * 创建标签
	 * @param  $openIds
	 * @param  $tagname
	 * @return mixed
	 */
	public static function createTag($tagname){ 
	       $tagname = self::PREFIX.$tagname;
	        $token = self::obtainAccessToken();
	        $url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=".$token;
	        $postData = array();
	        $postData['tag']['name']=$tagname; 
	        $rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($postData)),true);
	        //echo json_encode($rstdata);
	        return $rstdata; 
	}
	 
	/**
	 * 删除标签
	 * @param unknown $openIds
	 * @param unknown $tagname
	 */
	public static function delTag($openIds,$tagnames){
	    $rst = null;
	    foreach($tagnames as $tagname){
	        $tagname = self::PREFIX.$tagname;
	        $tagid = self::getTagByName($tagname);
    	    if(isset($tagid)){
    	        $token = self::obtainAccessToken();
    	        $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=".$token;
    	        $postData = array();
    	        if(is_array($openIds)){
    	            $postData['openid_list']=$openIds;
    	        }else{
    	            $postData['openid_list']=array($openIds);
    	        }
    	        $postData['tagid']=$tagid;
    	        $rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($postData)),true);; 
    	        //echo json_encode($rstdata);
    	        //return $rstdata;
    	        $rst = $rstdata;
    	    } 
	    }
	    return $rst;
	}
	/**
	 * 创建个性菜单
	 * @param unknown $data
	 * @param unknown $matchrule
	 */
	public static function createSpecialMenu($data){
	    $token = self::obtainAccessToken();
	    $url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=".$token;
	    $rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($data)),true);
        return $rstdata;
	}
	
	/**
	 * 创建菜单
	 * @param unknown $data
	 * @param unknown $matchrule
	 */
	public static function createMenu($data){
	    $token = self::obtainAccessToken();
	    $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$token;
	    $rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($data)),true);
	    return $rstdata;
	}
	
	/**
	 * 测试匹配
	 */
	public static function testSpecialMenu($openId){
	    $token = self::obtainAccessToken();
	    $url = "https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token=".$token;
	    $data = array();
	    $data['user_id']=$openId;
	    $rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($data)),true);
	    return $rstdata;
	}
	/**
	 * 菜单列表
	 * @return mixed
	 */
	public static function menuList(){
	    $token = self::obtainAccessToken();
	    $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$token; 
	    $rstdata = HttpUtil::curlGetJson($url);
	    return $rstdata;
	}
	
	public static function getUserByTagId($tagId){
	    $token = self::obtainAccessToken();
	    $url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=".$token;
	    $data = array();
	    $data['tagid']=$tagId;
	    $rstdata = json_decode(HttpUtil::curlPost($url,self::_jsonEncodeWithCN($data)),true);
	    return $rstdata;
	}
	 
	 
}